import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import LoadingWrapper from '../../components/LoadingWrapper';
import Card from './Card';
import TabBar from './TabBar';

@connect(({ picture, loading }) => ({
  pictures: picture.pictures,
  loading: !!loading.effects['picture/fetchPictures'],
}))
export default class Index extends PureComponent {
  static propTypes = {
    pictures: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
  };

  componentDidMount() {
    this.fetchPictures(1);
  }

  fetchPictures = type => {
    const { dispatch } = this.props;
    dispatch({
      type: 'picture/fetchPictures',
      payload: {
        params: {
          type,
        },
      },
    });
  };

  handleDetail = pid => {
    const { history } = this.props;
    history.push(`/detail?pid=${pid}`);
  };

  handleUserIndex = uid => {
    const { history } = this.props;
    history.push(`/pic/user?uid=${uid}`);
  };

  render() {
    const { pictures, loading } = this.props;

    return (
      <Fragment>
        <LoadingWrapper loading={loading}>
          {pictures.length > 0 &&
            pictures.map(item => (
              <Card
                key={item.id}
                picInfo={item}
                onDetail={this.handleDetail}
                onUserIndex={this.handleUserIndex}
              />
            ))}
        </LoadingWrapper>
        <TabBar onTypeChange={type => this.fetchPictures(type)} />
      </Fragment>
    );
  }
}
